﻿using System;
using Microsoft.Practices.Unity;

namespace CommonPatterns.IoC
{
    /// <summary>
    /// The boostraper to register app modules. This is the implementation of Dependecy injection pattern
    /// as defined in http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection
    /// using a construction injection.
    /// </summary>
    public class Bootstrapper
    {
        private IUnityContainer container;        

        public Bootstrapper(IUnityContainer container)
        {
            this.container = container;
        }

        #region Methods
        public Bootstrapper RegisterModule<T>() where T : IModule
        {
            Type type = typeof(T);
            return RegisterModule(type);
        }
        #endregion        

        #region Helper
        private Bootstrapper RegisterModule(Type type)
        {
            var module = container.Resolve(type) as IModule;
            if (module == null)
                throw new ArgumentException(string.Format("Unable to register the type [{0}]", type));
            module.Register(container);
            return this;
        }   
        #endregion   
    }
}
